import { Button, Checkbox, Form, Input, Row, Col, message } from 'antd';
import { useState } from 'react';
import { service } from '../../api/url.js'
import { sha1 } from 'sha1'
function Register(props) {
    let passwordCopy = ''
    let phone = ''
    const [hasCode, setHasCode] = useState(false)
    const [codeTime, setCodeTime] = useState(60)
    const [messageApi, contextHolder] = message.useMessage();
    const success = (msg) => {
        messageApi.open({
            type: 'success',
            content: msg,
        });
    };
      
    const error = (msg) => {
        messageApi.open({
            type: 'error',
            content: msg,
        });
    };
      
    const onFinish = (values) => {
        const params = {
            phone: values.phone,
            password: sha1(values.password),
            name: values.name,
            code: values.code
        }
        service.registerService(params).then(res => {
            console.log('--++', res)
            if (res.data.status === 1) {
                success(res.data.msg)
            } else {
                error(res.data.msg)
            }
        })
    };
    const onFinishFailed = (errorInfo) => {
      console.log('Failed:', errorInfo);
    };
    const onValuesChange = (changedValues, allValues) => {
        if (changedValues.hasOwnProperty('confirmPassword')) {
            passwordCopy = allValues.password
        }
        if (changedValues.hasOwnProperty('phone')) {
            phone = allValues.phone
        }
    }
    const returnTime = () => {
        let num = 60
        setCodeTime(num)
        let timer = setInterval(() => {
            setCodeTime(num--)
            if (num <= 0) {
                setHasCode(false)
                timer = clearInterval(timer)
            }
        }, 1000)
    }
    const getCode = () => {
        var reg = /^1[3456789]\d{9}$/;
        if (hasCode) {
            return
        }
        if (phone === '' || phone === undefined || !reg.test(phone)) {
            error('手机号不正确')
            return
        }
        service.getSmsCode({phone: phone}).then(res => {
            console.log('re---', res)
            if (res.data.status === 1) {
                setHasCode(true)
                returnTime()
                success(res.data.msg)
            } else {
                error(res.data.msg)
            }
        })
    }
    return (
        <div className="register">
            {contextHolder}
            <Form
                className="register-form"
                name="basic"
                labelCol={{
                  span: 8,
                }}
                wrapperCol={{
                  span: 16,
                }}
                style={{
                  maxWidth: 600,
                }}
                initialValues={{
                  remember: true,
                }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                onValuesChange={onValuesChange}
                autoComplete="off"
              >
                <Form.Item
                  label="手机号："
                  name="phone"
                  validateTrigger={['onChange', 'onBlur']}
                  rules={[
                    {
                      required: true,
                      message: '手机号不能为空!',
                      validateTrigger: ['onChange']
                    },
                    {
                        validator(_, value) {
                            var reg = /^1[3456789]\d{9}$/;
                            return value === '' || value === undefined || reg.test(value)  ? Promise.resolve() : Promise.reject('请输入正确的手机号')
                        },
                        validateTrigger: ['onBlur']
                    }
                  ]}
                >
                  <Input />
                </Form.Item>
              
                <Form.Item
                  label="用户名："
                  name="name"
                  rules={[
                    {
                      required: true,
                      message: '请输入用户名!',
                    }
                  ]}
                >
                  <Input />
                </Form.Item>
            
                <Form.Item
                  label="密码："
                  name="password"
                  rules={[
                    {
                      required: true,
                      message: '请输入密码!',
                    },
                  ]}
                >
                  <Input.Password />
                </Form.Item>
                
                <Form.Item
                  label="确认密码："
                  name="confirmPassword"
                  rules={[
                    {
                      required: true,
                      message: '请输入密码!',
                    },
                    {
                        validator(_, value) {
                            console.log(value, value === passwordCopy)
                            return value !== passwordCopy && value !== '' ? Promise.reject('两次密码不一致') : Promise.resolve()
                        }
                    }
                  ]}
                >
                  <Input.Password />
                </Form.Item>
                
                <Form.Item label="验证码：">
                        <Row gutter={20}>
                          <Col span={17}>
                            <Form.Item
                              name="code"
                              noStyle
                              rules={[
                                {
                                  required: true,
                                  message: '请输入验证码!',
                                },
                              ]}
                            >
                              <Input />
                            </Form.Item>
                          </Col>
                          <Col span={7}>
                            <Button onClick={getCode}>{hasCode ? codeTime + '秒后重新获取' : '获取验证码'}</Button>
                          </Col>
                        </Row>
                      </Form.Item>
                <Form.Item
                  wrapperCol={{
                    offset: 8,
                    span: 16,
                  }}
                >
                  <Button type="primary" htmlType="submit">
                    提交
                  </Button>
                </Form.Item>
              </Form>
        </div>
    )
}

export default Register